package com.rzjm.api.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rzjm.api.constant.ResponseCode;
import com.rzjm.api.entity.*;
import com.rzjm.api.service.*;
import com.rzjm.api.util.*;
import com.vdurmont.emoji.EmojiParser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  用户相关接口
 *@Date 2018-05-10
 */
@Component
@RequestMapping("/user")//url:模块/资源/{}/细分
public class UserController extends BaseController {

    @Resource
    private UserService userService;
    @Resource
    private UserMpService userMpService;
    @Resource
    private CkTerminalService ckTerminalService;
    @Resource
    private ShopService shopService;
    @Resource
    private SysErrorService sysErrorService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private WxTemplateService wxTemplateService;
    @Resource
    private WxModuleService moduleService;
    @Resource
    private SectionLinksService sectionLinksService;
    @Resource
    private ParameterService parameterService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private UserCarListService userCarListService;

    @Value("${web.imgprefix}")
    private String imgprefix;//图片地址

    @Value("${web.appidCy}")
    private String appidCy;//图片地址
    @Value("${web.secretCy}")
    private String secretCy;//图片地址

    @Value("${web.appid_mp}")
    private String appidMp;//图片地址
    @Value("${web.secret_mp}")
    private String secretMp;//图片地址

    /**微信登录
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/wxlogin",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject Login(@RequestBody String requestParam, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        try{
            logBefore(logger, "wxlogin  接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);

            String code = jsonRequest.containsKey("code") ? jsonRequest.getStr("code") : "";
            String platform = jsonRequest.containsKey("platform") ? jsonRequest.getStr("platform") : "check";
            String url = "https://api.weixin.qq.com/sns/jscode2session";
            Map<String,Object> mapParam = new HashMap<>();
            mapParam.put("appid",appidCy);
            mapParam.put("secret", secretCy);
            mapParam.put("js_code", code);
            mapParam.put("grant_type", "authorization_code");
            String returnParam = HttpUtil.httpClientPost(url, mapParam, "utf-8");
            logger.info("登录信息：" + returnParam);
            Gson gson = new Gson();
            Map<String, String> maps = gson.fromJson(returnParam, new TypeToken<Map<String, String>>() {}.getType());
            if(maps != null) {
                String openid = maps.containsKey("openid") ? maps.get("openid") : "";
                String unionid = maps.containsKey("unionid") ? maps.get("unionid") : "";
                String sessionkey =  maps.containsKey("session_key") ? maps.get("session_key") : "";
                if(!openid.equals("") && !sessionkey.equals("")) {
                    User user = userService.selectByUniqueColumn("open_id",openid);
                    if(user != null) {//老用户
                        //更新sessionkey
                        user.setUnionId(unionid);
                        user.setSessionKey(sessionkey);
                        user.setLastLoginIp(request.getRemoteAddr());
                        user.setLastActiveTime(new Date());
                        if(user.getIsAdmin() == null) {
                            user.setIsAdmin(0);
                        }
                        user.setPlatform(platform);
                        userService.updateById(user);
                    } else {//新用户
                        user = new User();
                        user.setPlatform(platform);
                        user.setOpenId(openid);
                        user.setUnionId(unionid);
                        user.setCreateTime(new Date());
                        user.setLastActiveTime(new Date());
                        user.setSessionKey(sessionkey);
                        user.setUserType(0);
                        user.setIsAdmin(0);
                        user.setShopId(0);
                        userService.save(user);
                    }

                    if(user.getUserNo() == null || user.getUserNo().equals("")){
                        String userno = "19" + String.format("%06d", user.getId());
                        user.setUserNo(userno);
                        userService.updateById(user);
                    }

                    Map<String ,Object> map = new HashMap<>();
                    map.put("userid",user.getId());
                    map.put("is_admin",user.getIsAdmin() == 1 ? 1:0);
                    map.put("is_mer",user.getUserType() == 1 ? 1:0);
                    map.put("shop_id",user.getShopId()!=null ? user.getShopId():0);
                    map.put("is_test",user.getIsTest());

                    Shop shop = shopService.selectById(user.getShopId());
                    if(shop != null){
                        int shop_user_id = shop.getUserId();
                        int userid = user.getId();
                        if(shop_user_id == userid){
                            map.put("is_super_admin",1);
                        }
                    }else{
                        map.put("shop_type",0);
                    }
//                    System.out.println("登录响应数据: " + map.toString());
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"登录成功",map),true,false);
                } else {
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"登录失败"),true,true);
                }
            } else {
                result = Tools.getJson(new GsonResultBean<>(-1,"系统异常"),true,true);
            }
        } catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("user/wxlogin",e);
        }
        return result;
    }

    /**获取用户信息
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/getUserInfoById",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject getUserInfoById(@RequestBody String requestParam, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        try{
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            logger.info("user/getUserInfoById:  "+ requestParam);
            System.out.println("getUserInfoById 接受参数：" + requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id"): 0;
            String platform = jsonRequest.containsKey("platform") ? jsonRequest.getStr("platform") : "check";
            User user = userService.findById(user_id);
            if(user != null){
                user.setLastActiveTime(new Date());
                user.setLastLoginIp(request.getRemoteAddr());
                userService.updateById(user);
                Map<String ,Object> map = new HashMap<String, Object>();
                map.put("userid",user.getId());
                map.put("is_admin",user.getIsAdmin() == 1 ? 1 : 0);
                map.put("is_mer",user.getUserType() == 1 ? 1 : 0);
                map.put("phone_num", StrUtil.isNotEmpty(user.getPhonenum()) ? user.getPhonenum() : "去绑定");
                map.put("shop_id",0);

                int groupId = 0;
                int userType = -1;
                map.put("town_name","");
                map.put("village_name","");
                map.put("real_name","");
                map.put("user_level","");
                map.put("role_name","");
                map.put("is_test",user.getIsTest());
                map.put("user_no", user.getUserNo());

                map.put("isOpenRange", 0);
                map.put("isOpenFirework", 0);
                map.put("isOpenZhili", 0);
                map.put("isOpenWelding", 0);
                map.put("is_band_sys",0);
                SysUser sysUser = sysUserService.getById(user.getSysUserId());
                if(sysUser != null){

                    map.put("isOpenRange", sysUser.getIsOpenRange());
                    map.put("isOpenFirework", sysUser.getIsOpenFirework());
                    map.put("isOpenZhili", sysUser.getIsOpenZhili());
                    map.put("isOpenWelding", sysUser.getIsOpenWelding());


                    map.put("is_band_sys",1);
                    map.put("user_type",sysUser.getUserType());
                    if(sysUser.getGroupId() != null){
                        groupId = sysUser.getGroupId();
                    }
                    userType = sysUser.getUserType();
                    if(StrUtil.isNotEmpty(sysUser.getTownName())){
                        map.put("town_name",sysUser.getTownName());
                    }
                    if(StrUtil.isNotEmpty(sysUser.getVillageName())){
                        map.put("village_name",sysUser.getVillageName());
                    }
                    if(sysUser.getUserLevel() != null){
                        if(sysUser.getUserLevel() == 1){
                            map.put("user_level", "县级");
                        } else if(sysUser.getUserLevel() == 2){
                            map.put("user_level", "镇级");
                        } else if(sysUser.getUserLevel() == 3){
                            map.put("user_level", "村级");
                        }
                    }
                    map.put("real_name",sysUser.getName());
                    SysRole sysRole = sysRoleService.findById(sysUser.getRoleId());
                    if(sysRole!=null){
                        map.put("role_name",sysRole.getRoleName());
                    }
                    map.put("is_call", sysUser.getIsCall());
                }

                Parameter parameter = parameterService.findById(1);
                if(parameter!=null){
                    map.put("platformName",parameter.getMallName());
                    map.put("platformTitle",parameter.getPlatformTitle());
                }

                Shop shop = shopService.selectById(user.getShopId());
                if(shop != null){
                    map.put("shop_name",shop.getShopName());
                    map.put("shop_id",shop.getId());
                }

                map.put("is_has_unionid",0);
                if(StrUtil.isNotEmpty(user.getUnionId())){
                    map.put("is_has_unionid",1);
                }

                if(groupId == 0){
                    groupId = 1;
                }
                if(platform.equals("check")){
                    List<WxModule> list = moduleService.getListByGroupId(groupId,user);
                    map.put("modules",list);
                } else if(platform.equals("cy")){
                    QueryWrapper<WxModule> qwModule = new QueryWrapper<>();
                    qwModule.eq("platform","cy");
                    qwModule.eq("state",1);
                    qwModule.orderByAsc("sort");
                    List<WxModule> list = moduleService.list(qwModule);
                    for (WxModule module : list) {
                        if (StrUtil.isNotEmpty(module.getIcon())) {
                            module.setIcon(imgprefix + module.getIcon());
                        }
                    }
                    map.put("modules",list);
                }
                else {
                    if(userType == 7){// 问卷调查
                        List<WxModule> list = moduleService.getSurveyList(user);
                        for (WxModule module : list) {
                            if (StrUtil.isNotEmpty(module.getIcon())) {
                                module.setIcon(imgprefix + module.getIcon());
                            }
                        }
                        map.put("modules",list);
                    }
//                    else if(userType != -1 && userType < 7){//巡检
//                        List<WxModule> list = moduleService.getListByGroupId(groupId,user);
//                        map.put("modules",list);
//                    }
                    else{
                        List<WxModule> list = moduleService.getSurveyList(user);
                        map.put("modules",list);
                    }
                }

                if(!(platform.equals("check") || platform.equals("cy") || platform.equals("co") || platform.equals("car"))){
                    map.put("weather", WeatherUtil.getWeatherInfo("101120903"));
                }else{
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.set("weatherinfo","");
                    map.put("weather", jsonObject);
                }

                QueryWrapper<SectionLinks> qw = new QueryWrapper<>();
                qw.eq("state",1);
                qw.orderByAsc("sort");
                List<SectionLinks> links = sectionLinksService.list(qw);
                if(CollUtil.isNotEmpty(links)){
                    for (SectionLinks link : links){
                        link.setImgUrl(imgprefix + link.getImgUrl());
                    }
                }
                map.put("banners",links);

                if(user_id > 0){
                    QueryWrapper<UserCarList> qwCar = new QueryWrapper<>();
                    qwCar.eq("user_id",user_id);
                    long carCount = userCarListService.count(qwCar);
                    map.put("carCount", carCount);
                }


                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            sysErrorService.insertSelective("user/getUserInfo",e);
        }
        return result;
    }

    /**
     * 绑定手机号
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/getWxPhoneNum",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject getWxPhoneNum(@RequestBody String requestParam, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "user/getWxPhoneNum  接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            Integer user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String code = jsonRequest.containsKey("code") ? jsonRequest.getStr("code") : "";
            String platform = jsonRequest.containsKey("platform") ? jsonRequest.getStr("platform") : "check";
            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

            String accessToken = wxTemplateService.getAccessToken(appidCy,secretCy,0);

            String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
            Map<String,Object> mapParam = new HashMap<>();
            mapParam.put("code", code);
            String returnParam = OkHttpClientUtil.getInstance().postJson(url, JSONUtil.toJsonStr(mapParam));
//            String jsonStr = returnParam.body().string();
            System.out.println("返回信息：" + returnParam);
            JSONObject userJson = JSONUtil.parseObj(returnParam);
            if(userJson!= null){
                if(userJson.getInt("errcode") == 0){
                    String phone = userJson.getJSONObject("phone_info").getStr("purePhoneNumber");
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"获取成功",phone),true,false);
                }else{
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"获取失败"),true,true);
                }
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"获取失败"),true,true);
            }
        } catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**获取用户信息
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/getUserInfo",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject getUserInfo(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String encryptedData = jsonRequest.containsKey("encryptedData") ? jsonRequest.getStr("encryptedData") : "";
            String iv = jsonRequest.containsKey("iv") ? jsonRequest.getStr("iv") : "";
            String rawData = jsonRequest.containsKey("rawData") ? jsonRequest.getStr("rawData") : "";

            System.out.println("getUserInfo 接受参数：" + requestParam);
            logger.info("user/getUserInfo:  "+ requestParam);

            String userInfo = "",unionId = "",nickname = "",faceurl = "",city = "",province="";
            int gender = 1;
            User user = userService.findById(user_id);
            if(user != null){
                userInfo = AESUtil.decryptWXAppletInfo(encryptedData,user.getSessionKey(),iv);
                JSONObject decodeJSON = null;
                if(userInfo!=null && !userInfo.equals("")){
                    try {
                        decodeJSON = JSONUtil.parseObj(userInfo);
                        if(decodeJSON != null && decodeJSON.size() > 0){
                            unionId = decodeJSON.containsKey("unionId") ? decodeJSON.getStr("unionId") :"";
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                }
                String ssss = "";
                JSONObject userInfoJson = null;
                if(!rawData.equals("")){
                    userInfoJson = JSONUtil.parseObj(rawData);
                    if(userInfoJson != null && userInfoJson.size() > 0){
                        if(nickname.equals("")){
                            System.out.println("");
                            System.out.println("nickname 处理前: " + nickname);
                            logger.info("nickname 处理前: " + nickname);
                            nickname = userInfoJson.containsKey("nickName") ? userInfoJson.getStr("nickName") : user.getNickName();
                            nickname = EmojiParser.parseToAliases(nickname);
//                            ssss = EmojiParser.parseToUnicode(nickname);
                            System.out.println("nickname 处理后: " + nickname);
                            logger.info("nickname 处理后: " + nickname);
                            System.out.println("");
                        }
                        if(faceurl.equals("")){
                            faceurl = userInfoJson.containsKey("avatarUrl") ? userInfoJson.getStr("avatarUrl") : user.getFaceUrl();
                        }
                        if(city.equals("")){
                            city = userInfoJson.containsKey("city")? userInfoJson.getStr("city") : user.getCity();
                        }
                        if(province.equals("")){
                            province = userInfoJson.containsKey("province") ? userInfoJson.getStr("province") : user.getProvince();
                        }
                        gender = userInfoJson.containsKey("gender") ? Integer.parseInt(userInfoJson.get("gender").toString()):1;
                    }
                }

                if(!unionId.equals("")){
                    user.setUnionId(unionId);
                }
                if(!nickname.equals("")){
                    user.setNickName(nickname);
                }
                if(!faceurl.equals("")){
                    user.setFaceUrl(faceurl);
                }
                if(!city.equals("")){
                    user.setCity(city);
                }
                if(!province.equals("")){
                    user.setProvince(province);
                }
                userService.updateById(user);

                Map<String ,Object> map = new HashMap<String, Object>();
                map.put("userid",user.getId());
                map.put("is_admin",user.getIsAdmin() == 1 ? 1 : 0);
                map.put("is_mer",user.getUserType() == 1 ? 1 : 0);
                map.put("is_test",user.getIsTest());
                map.put("shop_id",0);
                map.put("phone_num",user.getPhonenum());
                SysUser sysUser = sysUserService.getById(user.getSysUserId());
                if(sysUser!=null){
                    map.put("user_type",sysUser.getUserType());
                    Shop shop = shopService.selectById(sysUser.getShopId());
                    if(shop!=null){
                        map.put("shop_name",shop.getShopName());
                        map.put("shop_id",shop.getId());
                    }
                }
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"用户不存在"),true,true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            sysErrorService.insertSelective("user/getUserInfo",e);
        }
        return result;
    }

    /**
     *  获取用户个人中心的显示数据  包括 优惠券的数量 底部广告，订单类型的数量
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/getUserInfoData",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject getUserInfoData(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int user_type = jsonRequest.containsKey("user_type") ? jsonRequest.getInt("user_type") : 0;
            //订单状态 0 - 未支付   1 - 已支付，待发货  2 - 已发货， 待收货  3 - 已收货，待评价 4 - 已评价  5 - 订单取消  6 - 已申请退货  7 - 同意退货  8 - 拒绝退货 9 - 完成退款
            //1.获取订单类型的数量  待付款、待发货、已发货、待评价、售后

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }
            map.put("phone_num",user.getPhonenum());
            map.put("shop_id",0);
            map.put("is_test",user.getIsTest());
            SysUser sysUser = sysUserService.getById(user.getSysUserId());
            if(sysUser!=null){
                map.put("user_type",sysUser.getUserType());
                map.put("real_name",sysUser.getName());
                Shop shop = shopService.selectById(sysUser.getShopId());
                if(shop!=null){
                    map.put("shop_name",shop.getShopName());
                    map.put("shop_id",shop.getId());
                }
//                Company company = companyService.findById(sysUser.getCompanyId());
//                if(company != null){
//                    map.put("company_name",company.getCompanyName());
//                }

                Department department = departmentService.findById(sysUser.getDeptId());
                if(department!=null){
                    map.put("department_name",department.getName());
                }
                map.put("is_call", sysUser.getIsCall());
            }
            QueryWrapper<UserCarList> userCarListQueryWrapper = new QueryWrapper<>();
            userCarListQueryWrapper.eq("state", 1);
            userCarListQueryWrapper.eq("user_id", user_id);
            Long userCarListCount = userCarListService.count(userCarListQueryWrapper);
            if (userCarListCount != null && userCarListCount > 0){
                map.put("myCarBindInfo","已绑定");
            }else {
                map.put("myCarBindInfo","去绑定");
            }
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"获取成功",map),true,false);

        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            sysErrorService.insertSelective("user/getUserInfoData",e);
        }
        return result;
    }

    /**
     * 发送验证码
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "sendCode", method = {RequestMethod.POST}, produces = "application/json;charset=utf-8")
    @ResponseBody
    public JSONObject sendValidateCode(@RequestBody String requestParam) throws Exception {
        JSONObject result = null;
        try {
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            String phoneNum = jsonRequest.containsKey("phoneNum") ? jsonRequest.getStr("phoneNum") : null;
            Integer codetype = jsonRequest.containsKey("codetype") ? jsonRequest.getInt("codetype") : null;

            if (!phoneNum.equals("") && phoneNum.length() == 11 && Tools.checkMobileNumber(phoneNum)) {
//                SmsTemplate sms = smsTemplateService.selectByUniqueColumn("code_type",codetype);
//                if(sms == null){
//                    return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "发送失败"), true, true);
//                }
                //验证码
//                int code = Tools.getRandomNum();//生成6位随机数
//                SendSms sendSms = new SendSms();
//                //请求失败这里会抛ClientException异常
//                JSONObject smsJson = new JSONObject();
//                smsJson.put("code", code);
//                SendSmsResponse sendSmsResponse = sendSms.send(phoneNum,smsJson,sms);
//                if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
//                    redisTemplate.opsForValue().set(phoneNum, code, 300L, TimeUnit.SECONDS);
//                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"发送成功"),true,false);
//                }else {
//                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"验证码发送失败，请重试"),true,true);
//                }
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"请输入正确的手机号"),true,true);
            }
        }catch(Exception e){
            e.printStackTrace();
            sysErrorService.insertSelective("user/sendCode",e);
            System.out.println(""+e.getMessage());
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"系统异常"),true,true);
        }
        return result;
    }


    /** 修改会员卡信息  只有在 没有这个保单 和 没有保单的情况下 才能修改
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/bandPhone",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject bandPhone(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(requestParam.equals("")){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "bandPhone 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String phone_num = jsonRequest.containsKey("phone_num") ? jsonRequest.getStr("phone_num").trim() : "";
            String code = jsonRequest.containsKey("code") ? jsonRequest.getStr("code") : "";
            String plat_form = jsonRequest.containsKey("plat_form") ? jsonRequest.getStr("plat_form") : "";
            int user_type = jsonRequest.containsKey("user_type") ? jsonRequest.getInt("user_type") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            phone_num = phone_num.replaceAll("去绑定","");
            if(StrUtil.isEmpty(phone_num)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"手机号不能为空"),true,true);
            }

            QueryWrapper<SysUser> qw = new QueryWrapper<>();
            qw.eq("mobile",phone_num);
            if(user_type > 0){
                qw.eq("user_type",user_type);
            }
            qw.last(" LIMIT  1");
            SysUser sysUser = sysUserService.getOne(qw);
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "该手机号人员不存在"), true , true);
            }

            QueryWrapper<User> qwUser = new QueryWrapper<>();
            qwUser.eq("sys_user_id", sysUser.getUserId());
            qwUser.eq("platform", plat_form);
            long userCount = userService.selectCountByQueryWrapper(qwUser);
            if(userCount > 0) {
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "该手机号已被用户绑定"), true , true);
            }
            Map<String,Object> map = new HashMap<>();
            map.put("shop_name","");
            map.put("phone_num",phone_num);
            map.put("shop_id",0);
            user.setShopId(sysUser.getShopId());
            user.setSysUserId(sysUser.getUserId());
            user.setPhonenum(phone_num);
            boolean bl = userService.updateById(user);
            if(bl){
                Shop shop = shopService.selectById(sysUser.getShopId());
                if(shop != null){
                    map.put("shop_name",shop.getShopName());
                    map.put("shop_id",shop.getId());
                }
                if(sysUser!=null){
                    map.put("user_type",sysUser.getUserType());
                    map.put("real_name",sysUser.getName());
//                    Company company = companyService.findById(sysUser.getCompanyId());
//                    if(company != null){
//                        map.put("company_name",company.getCompanyName());
//                    }

                    Department department = departmentService.findById(sysUser.getDeptId());
                    if(department!=null){
                        map.put("department_name",department.getName());
                    }
                }
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "绑定成功",map), true , false);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "绑定失败"), true , true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            sysErrorService.insertSelective("user/bandPhone",e);
        }
        return result;
    }


    /** 修改会员卡信息  只有在 没有这个保单 和 没有保单的情况下 才能修改
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/getUserListByName",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject getUserListByName(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(requestParam.equals("")){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "bandPhone 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String name = jsonRequest.containsKey("name") ? jsonRequest.getStr("name").trim() : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            Map<String,Object> map = new HashMap<>();
            QueryWrapper<SysUser> qw = new QueryWrapper<>();
            qw.eq("name",name);
            List<SysUser> users = sysUserService.list(qw);

            map.put("users", users);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "查询成功",users.size(),users), false , false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            sysErrorService.insertSelective("user/bandPhone",e);
        }
        return result;
    }

    /** 修改会员卡信息  只有在 没有这个保单 和 没有保单的情况下 才能修改
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/bandManagerByName",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject bandManagerByName(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(requestParam.equals("")){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "bandPhone 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int sys_user_id = jsonRequest.containsKey("sys_user_id") ? jsonRequest.getInt("sys_user_id") : 0;
            int role_id = jsonRequest.containsKey("role_id") ? jsonRequest.getInt("role_id") : 0;
            String phone_num = jsonRequest.containsKey("phone_num") ? jsonRequest.getStr("phone_num").trim() : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.findById(sys_user_id);
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该绑定排查人不存在"),true,true);
            }
            user.setSysUserId(sysUser.getUserId());
            user.setPhonenum(phone_num);
            boolean bl = userService.updateById(user);
            if(bl){
                sysUser.setUsername(phone_num);
                sysUser.setMobile(phone_num);
                sysUser.setRoleId(role_id);
                SysRole sysRole = sysRoleService.findById(role_id);
                if(sysRole!=null){
                    sysUser.setUserType(sysRole.getUserType());
                }
                sysUser.setPassword(MD5Utils.encrypt(phone_num, "123456"));
                bl = sysUserService.updateById(sysUser);
                if(bl){
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "绑定成功"), true , false);
                }else{
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "绑定失败"), true , false);
                }
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "绑定失败"), true , false);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            sysErrorService.insertSelective("user/bandPhone",e);
        }
        return result;
    }


    /** 修改会员卡信息  只有在 没有这个保单 和 没有保单的情况下 才能修改
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/bandShop",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject bandShop(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(requestParam.equals("")){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "bandShop 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String shop_no = jsonRequest.containsKey("shop_no") ? jsonRequest.getStr("shop_no").trim() : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            Shop shop = shopService.selectByUniqueColumn("shop_no",shop_no);
            if(shop == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前企业不存在"),true,true);
            }

            if(shop.getState() != 1){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前企业不可用"),true,true);
            }

            if(user.getShopId() !=0  && user.getShopId().intValue() != shop.getId().intValue()){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您已经有绑定企业"),true,true);
            }
            user.setShopId(shop.getId());
            SysUser sysUser = sysUserService.getById(user.getSysUserId());
            if(sysUser != null){
                sysUser.setShopId(shop.getId());
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请先绑定手机号"),true,true);
            }
            int ret = userService.bandShop(user,sysUser);
            if(ret > 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "绑定成功",shop), true , false);
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "绑定失败"), true , true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            sysErrorService.insertSelective("user/bandShop",e);
        }
        return result;
    }

    /**
     * 修改会员卡信息  只有在 没有这个保单 和 没有保单的情况下 才能修改
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/unBandShop",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject unBandShop(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(requestParam.equals("")){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "user/unBandShop 接收的参数： "+requestParam);
            System.out.println("user/unBandShop 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int shop_id = jsonRequest.containsKey("shop_id") ? jsonRequest.getInt("shop_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.getById(user.getSysUserId());
            if(sysUser != null){
                if((sysUser.getUserType() >= 4  && sysUser.getUserType() <= 7) && sysUser.getShopId() == 0){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定企业"),true,true);
                }
            }

            Shop shop = shopService.selectById(shop_id);
            if(shop == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前企业不存在"),true,true);
            }

            int ret = userService.unBandShop(user,sysUser,shop_id);
            if(ret > 0){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "解绑成功"), true , true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "解绑失败"), true , true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            sysErrorService.insertSelective("user/unBandShop",e);
        }
        return result;
    }

    /**  获取当前商户下的所有管理员的列表（包含产生的订单数量）
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/getAdminList",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject getAdminList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            System.out.println("getAdminList 接收的参数： "+requestParam);
            logBefore(logger, "接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int pageIndex = jsonRequest.containsKey("pageindex") ? jsonRequest.getInt("pageindex") : 1;
            int pageSize = jsonRequest.containsKey("pagesize") ? jsonRequest.getInt("pagesize") : 10;
            int offset = (pageIndex - 1) * pageSize;

            User user = userService.findById(user_id);
            if(user == null){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
                return result;
            }

            Shop shop = shopService.selectByUserId(user_id);
            if(shop!=null){
                if(user_id == shop.getUserId()){//只有最高权限的管理员  才能查看
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    //获取当前月第一天：
                    Calendar c_first = Calendar.getInstance();
                    c_first.add(Calendar.MONTH, 0);
                    c_first.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
                    String first = format.format(c_first.getTime())+" 00:00:00";
                    System.out.println("===============first:"+first);
                    Date first_date = DateUtil.ConvertDateByformat(first,"yyyy-MM-dd HH:mm:ss");

                    //获取当前月最后一天
                    Calendar c_last = Calendar.getInstance();
                    c_last.set(Calendar.DAY_OF_MONTH, c_last.getActualMaximum(Calendar.DAY_OF_MONTH));
                    String last = format.format(c_last.getTime())+" 23:59:59";
                    System.out.println("===============last:"+last);
                    Date last_date = DateUtil.ConvertDateByformat(last,"yyyy-MM-dd HH:mm:ss");

                    List<User> list = userService.selectByShopId(shop.getId(),user_id,offset,pageSize,first_date,last_date);
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功", list.size(), list),false,false);
                }else{
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您没有该权限"),true,true);
                }
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您没有该权限"),true,true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("user/getAdminList",e);
        }
        return result;
    }


    /**  获取骑手信息（昵称）
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/userDetail",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject couponDetail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int bang_user_id = jsonRequest.containsKey("bang_user_id") ? jsonRequest.getInt("bang_user_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            Shop shop = shopService.selectByUserId(user_id);
            if(shop!=null){
                User band_user = userService.findById(bang_user_id);
                if(band_user != null){
                    if(band_user.getNickName()!=null){
                        map.put("nick_name",EmojiParser.parseToUnicode(band_user.getNickName()));
                    }else{
                        map.put("nick_name",band_user.getNickName());
                    }
                    map.put("bang_user_id",band_user.getId());
                    map.put("phone_num",band_user.getPhonenum());
                    if(band_user.getShopId() == shop.getId()){//已经绑定了
                        map.put("bang_state",1);
                    }else{
                        map.put("bang_state",0);
                    }
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
                }else{
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
                }
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您没有该权限"),true,true);
            }

        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("user/userDetail",e);
        }
        return result;
    }

    /**  获取骑手信息（昵称）
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/bandAdmin",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject bandAdmin(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            logBefore(logger, "接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int bang_user_id = jsonRequest.containsKey("bang_user_id") ? jsonRequest.getInt("bang_user_id") : 0;
            int band_type = jsonRequest.containsKey("band_type") ? jsonRequest.getInt("band_type") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            Shop shop = shopService.selectByUserId(user_id);
            if(shop!=null){
                User band_user = userService.findById(bang_user_id);
                if(band_user != null){
                    int ret = 0;
                    boolean bl = false;
                    if(band_type == 0){ //取消绑定
                        band_user.setShopId(0);
                        band_user.setUserType(0);
                        bl = userService.updateById(band_user);
                        if(bl){
                            ret = 1;
                        }
                    }else{  //绑定
                        if(band_user.getShopId() == 0){   //已经绑定了
                            band_user.setShopId(shop.getId());
                            band_user.setUserType(1);
                            bl = userService.updateById(band_user);
                            if(bl){
                                ret = 1;
                            }
                        }else if(band_user.getShopId() == shop.getId()){
                            ret = -1;
                        }else if(band_user.getShopId() != shop.getId() && band_user.getShopId() != 0){
                            ret = -2;
                        }
                    }
                    if(ret > 0){
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"操作成功"),true,true);
                    }else if(ret == -1){
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户已绑定该商家"),true,true);
                    }else if(ret == -2){
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户已绑定其他商家"),true,true);
                    }else{
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"操作失败"),true,true);
                    }
                }else{
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
                }
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您没有该权限"),true,true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("user/bandAdmin",e);
        }
        return result;
    }



    /**  同步微信公众号用户
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/initMpUser",method = {RequestMethod.POST,RequestMethod.GET},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject initMpUser() throws Exception{
        JSONObject result = null;
        try{
            String accessToken = wxTemplateService.getAccessToken(appidMp,secretMp,1);
            System.out.println("accessToken:" + accessToken);
            JSONObject jsonObject = WxMessage.getUserMp(accessToken,"");
            int userCount = 0;
            if(jsonObject!=null){
                System.out.println(jsonObject.toString());
                JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("openid");
                if(jsonArray != null && jsonArray.size() > 0) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        String openid = jsonArray.getStr(i);
                        JSONObject userInfo = WxMessage.getUserMpInfo(accessToken,openid);
                        if(userInfo!=null && userInfo.size() > 0){
                            String openId = userInfo.getStr("openid");
                            String unionId = userInfo.getStr("unionid");
                            String nickname = userInfo.getStr("nickname");
                            String faceurl = userInfo.getStr("headimgurl");
                            UserMp userMp = userMpService.selectByUniqueColumn("unionid",unionId);
                            boolean bl = false;
                            if(userMp == null){
                                userMp = new UserMp();
                                userMp.setOpenid(openId);
                                userMp.setUnionid(unionId);
                                userMp.setFaceUrl(faceurl);
                                userMp.setNickName(nickname);
                                userMp.setCreateTime(new Date());
                                if(StrUtil.isNotEmpty(openId)){
                                    bl = userMpService.save(userMp);
                                }
                                if(bl){
                                    userCount++;
                                }
                            }
                        }
                    }
                }
            }
            return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"共成功添加" + userCount+"个用户"),true,true);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("user/initMpUser",e);
        }
        return result;
    }


    /**  推送微信公众号的模板消息   测试用
     * @param
     * @throws Exception
     */
    @RequestMapping(value="/sendWxMsg",method = {RequestMethod.POST,RequestMethod.GET},produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject sendWxMsg(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            logBefore(logger, "接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int terminal_id = jsonRequest.containsKey("terminal_id") ? jsonRequest.getInt("terminal_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }
            CkTerminal terminal = ckTerminalService.findById(terminal_id);
            if(terminal == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"终端不存在"),true,true);
            }
            WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",1);
            UserMp userMp = userMpService.selectByUniqueColumn("unionid",user.getUnionId());
            if(userMp!=null){

                WxMsgTemplate template = new WxMsgTemplate();
                template.setTouser(userMp.getOpenid());
                template.setTemplate_id(wxTemplate.getTemplateId());
                template.setUrl("");
                Map<String, MsgTempData> m = new HashMap<String, MsgTempData>();

                MsgTempData first = new MsgTempData();
                first.setColor("#173177");
                first.setValue("管理员您好，有设备出现报修警报");
                m.put("first",first);

                //设备名称
                MsgTempData keyword1 = new MsgTempData();
                keyword1.setColor("#173177");
                keyword1.setValue(terminal.getTerminalName());
                m.put("keyword1",keyword1);

                //设备编号
                MsgTempData keyword2 = new MsgTempData();
                keyword2.setColor("#173177");
                keyword2.setValue(terminal.getTerminalNum());
                m.put("keyword2",keyword2);

                //在线状态
                MsgTempData keyword3 = new MsgTempData();
                keyword3.setColor("#173177");
                keyword3.setValue("设备在线");
                m.put("keyword3",keyword3);

                //最后时间
                MsgTempData keyword4 = new MsgTempData();
                keyword4.setColor("#173177");
                keyword4.setValue(DateUtil.getTime());
                m.put("keyword4",keyword4);

                //设备状态
                MsgTempData keyword5 = new MsgTempData();
                keyword5.setColor("#FF5722");
                keyword5.setValue("该设备存在异常报修，请及时处理");
                m.put("keyword5",keyword5);


                MsgTempData remark = new MsgTempData();
                remark.setColor("#173177");
                remark.setValue("感谢你使用智能设备！");
                m.put("remark",remark);
                template.setData(m);

//                System.out.println("模板消息：" + template.toString());

                String param = JSONUtil.parseObj(template).toString();
                String accessToken = wxTemplateService.getAccessToken(appidMp,secretMp, 1);
                JSONObject jsonObject = WxMessage.sendMsg(accessToken,param);
                if(jsonObject!=null){
                    System.out.println("jsonObject:" + jsonObject.toString());
                }
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(-1,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            sysErrorService.insertSelective("user/initMpUser",e);
        }
        return result;
    }


}
